package com.example.springboot.dao;

import com.example.springboot.entity.Permission;
import com.example.springboot.util.JdbcTemplateUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by tang on 2018/1/5.
 */
public class PermissionDao {

    private JdbcTemplate jdbcTemplate;

    {
        jdbcTemplate = JdbcTemplateUtils.jdbcTemplate();
    }

    public Permission createPermssion(final Permission permission) {
        final String sql = "insert into sys_permissions(permission,description,available) value(?,?,?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
                psst.setString(1, permission.getPermission());
                psst.setString(2, permission.getDescription());
                psst.setBoolean(3, permission.getAvailable());

                return psst;
            }
        }, keyHolder);

        permission.setId(keyHolder.getKey().longValue());

        return permission;
    }


    public void deletePermission(Long permissionId) {
        //首先把与permission关联的相关表数据都删掉
        String sql = "delete from sys_roles_permissions where permission_id=?";
        jdbcTemplate.update(sql, permissionId);

        sql = "delete from sys_permissions where id=?";
        jdbcTemplate.update(sql, permissionId);
    }
}
